#import "USRealtimeLocationManager.h"
#import <CoreLocation/CoreLocation.h>
#import <HyphenateChat/HyphenateChat.h>
#import "USLocationInfo.h"

@interface USRealtimeLocationManager () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSTimer *dispatchTimer;
@property (nonatomic, assign) NSTimeInterval dispatchInterval;
@property (nonatomic, assign) BOOL isDispatching;

@end

@implementation USRealtimeLocationManager

+ (instancetype)shared {
    static USRealtimeLocationManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[USRealtimeLocationManager alloc] init];
    });
    return instance;
}

#pragma mark - Public Methods

- (void)startDispatchingWithInterval:(NSTimeInterval)interval {
    self.dispatchInterval = interval;

    if (self.isDispatching || self.dispatchInterval) {
        [self.dispatchTimer invalidate];
        self.dispatchTimer = nil;
    }

    self.isDispatching = YES;

    [self setupLocationManager];
    [self.locationManager startUpdatingLocation];

    self.dispatchTimer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                          target:self
                                                        selector:@selector(sendLocation)
                                                        userInfo:nil
                                                         repeats:YES];

    [self sendLocation]; // 启动时立即发一次
}

- (void)stopDispatching {
    if (!self.isDispatching) return;

    self.isDispatching = NO;

    [self.dispatchTimer invalidate];
    self.dispatchTimer = nil;

    [self.locationManager stopUpdatingLocation];
}

#pragma mark - CLLocationManager Setup

- (void)setupLocationManager {
    if (!self.locationManager) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [self.locationManager requestAlwaysAuthorization];
    }
}

#pragma mark - Send Location via EMCustomMessage

- (void)sendLocation {
    if (!self.isDispatching) return;

    CLLocation *loc = self.locationManager.location;
    if (!loc) return;

    double lat = loc.coordinate.latitude;
    double lng = loc.coordinate.longitude;
    NSTimeInterval time = [loc.timestamp timeIntervalSince1970];
    
    NSString *latStr = [NSString stringWithFormat:@"%.15f", lat];
    NSString *lngStr = [NSString stringWithFormat:@"%.15f", lng];
    NSString *timeStr = [NSString stringWithFormat:@"%.0f", time];

    NSDictionary *ext = @{
        @"lat": latStr,
        @"lng": lngStr,
        @"timestamp": timeStr
    };
    
    EMCmdMessageBody *body = [[EMCmdMessageBody alloc] initWithAction:@"realtime_location"];
    body.isDeliverOnlineOnly = YES; // 不存消息
    EMChatMessage *msg = [[EMChatMessage alloc] initWithConversationID:USUser.user.relImUserName body:body ext:ext];
    
    [[EMClient sharedClient].chatManager sendMessage:msg progress:nil completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
        if (error) {
            NSLog(@"❌ 位置发送失败：%@", error.errorDescription);
        } else {
            NSLog(@"✅ 实时位置已发送：%@", ext);
        }
    }];
    
    
    
}

- (void)saveRelUserLocationInfo:(NSDictionary *)info{
    
    NSLog(@"%@",info);
    [[NSUserDefaults standardUserDefaults]setObject:info forKey:KeyRelUserLocationInfo];
}


- (USLocationInfo *)relUserLocationInfo{
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults]dictionaryForKey:KeyRelUserLocationInfo];
    
    if (!dic) {
        return nil;
    }
    
    USLocationInfo *info = [USLocationInfo mj_objectWithKeyValues:dic];
    return info;
    
}


@end
